package per.zhang.serverPrevioder.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import per.zhang.serverPrevioder.base.dto.ResultDTO;
import per.zhang.serverPrevioder.base.page.PageList;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import per.zhang.serverPrevioder.base.page.Paginator;
import per.zhang.serverPrevioder.base.utils.AppointmentStateCode;
import per.zhang.serverPrevioder.base.utils.ResultUtil;
import per.zhang.serverPrevioder.dto.request.AppointmentRequestDTO;
import per.zhang.serverPrevioder.dto.respone.AppointmentRespondDTO;
import per.zhang.serverPrevioder.entity.Appointment;
import per.zhang.serverPrevioder.entity.Vaccine;
import per.zhang.serverPrevioder.service.AppointmentService;
import per.zhang.serverPrevioder.service.VaccineService;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 *
 * @author Zhang
 * @since 2021-01-25
 */
@RestController
@RequestMapping("/appointment")
@CrossOrigin
@Slf4j
public class AppointmentController {

        @Autowired
        private AppointmentService appointmentService;


        @Autowired
        private VaccineService vaccineService;

        @PostMapping("/adminGetAppointment")
        @ApiOperation(value = "管理员查看疫苗接种预定")
        public ResultDTO adminGetAppointment(@RequestBody AppointmentRequestDTO appointmentRequestDTO) throws Exception{
            PageList<AppointmentRespondDTO> result = null;
            List<AppointmentRespondDTO> resultData = new ArrayList<>();
            try {
                List<Appointment> data = new ArrayList<>();
                Appointment appointment = new Appointment();
                appointment.setAppointmentTime(appointmentRequestDTO.getAppointmentTime());
                appointment.setState(AppointmentStateCode.APPOINTING);
                List<Appointment> list1 = appointmentService.findByParams(appointment, "creat_time DESC");
                data.addAll(list1);
                appointment.setState(AppointmentStateCode.VACCINATION);
                List<Appointment> list2 = appointmentService.findByParams(appointment, "creat_time DESC");
                data.addAll(list2);
                Paginator paginator = new Paginator(appointmentRequestDTO.getPageNum(), appointmentRequestDTO.getPageSize(), data.size());
                result = new PageList<AppointmentRespondDTO>(paginator);
                //分页
                if (data !=null && data.size()>0) {
                    int currIdx = (appointmentRequestDTO.getPageNum() > 1 ? (appointmentRequestDTO.getPageNum() - 1) * appointmentRequestDTO.getPageSize(): 0);
                    for (int i = 0; i < appointmentRequestDTO.getPageSize() && i < data.size() - currIdx; i++) {
                        Appointment item = data.get(currIdx + i);
                        item.setState(AppointmentStateCode.STATE_CODE_MAP.get(item.getState()));
                        Vaccine vaccine = vaccineService.get(item.getVaccineId());
                        AppointmentRespondDTO appointmentRespondDTO = new AppointmentRespondDTO(item, vaccine.getVaccineName(),vaccine.getVaccineId());
                        resultData.add(appointmentRespondDTO);
                    }
                }
                result.setData(resultData);
            } catch (Exception e) {
                return ResultUtil.Error("500",e.getMessage());
            }
            return ResultUtil.Success(result);
        }

        @PostMapping("/userAppointment")
        @ApiOperation(value = "用户预约打疫苗")
        //@ApiImplicitParams()
        public ResultDTO userAppointment( @RequestBody Appointment appointment)throws Exception{
            try {
                Vaccine vaccine = vaccineService.get(appointment.getVaccineId());
                if (vaccine.getAppointmentNum()<=0) {
                    return ResultUtil.Error("500","余量不足");
                }
                vaccine.setAppointmentNum(vaccine.getAppointmentNum()-1);
                appointment.setCreatTime(new Date());
                appointment.setState(AppointmentStateCode.APPOINTING);
                appointmentService.save(appointment);

                vaccineService.update(vaccine);
            } catch (Exception e) {
                return ResultUtil.Error("500",e.getMessage());
            }
            return ResultUtil.Success(appointment);
        }

        @PostMapping("/userCancelAppointment")
        @ApiOperation(value = "用户取消打疫苗")
        //@ApiImplicitParams()
        public ResultDTO userCancelAppointment( @RequestBody Appointment appointment)throws Exception{
            try {
                appointment.setState(AppointmentStateCode.CANCELED);
                appointmentService.update(appointment);
                Vaccine vaccine = vaccineService.get(appointment.getVaccineId());
                vaccine.setAppointmentNum(vaccine.getAppointmentNum()+1);
                vaccineService.update(vaccine);
            } catch (Exception e) {
                return ResultUtil.Error("500",e.getMessage());
            }
            return ResultUtil.Success(appointmentService.get(appointment.getAppointmentId()));
        }

        @PostMapping("/adminVaccination")
        @ApiOperation(value = "管理员确认接种疫苗")
        //@ApiImplicitParams()
        public ResultDTO adminVaccination( @RequestBody Appointment appointment)throws Exception{
            try {
                appointment.setState(AppointmentStateCode.VACCINATION);
                appointmentService.update(appointment);
                Vaccine vaccine = vaccineService.get(appointment.getVaccineId());
                vaccine.setSurplusNum(vaccine.getSurplusNum()-1);
                vaccineService.update(vaccine);
            } catch (Exception e) {
                return ResultUtil.Error("500",e.getMessage());
            }
            return ResultUtil.Success(appointmentService.get(appointment.getAppointmentId()));
        }

        @PostMapping("/insertAppointment")
        @ApiOperation(value = "插入一条数据")
        //@ApiImplicitParams()
        public ResultDTO insertOne( @RequestBody Appointment appointment)throws Exception{
            try {

                appointmentService.save(appointment);
            } catch (Exception e) {
                return ResultUtil.Error("500",e.getMessage());
            }
            return ResultUtil.Success(appointment);
        }

        @PostMapping("/updateById")
        @ApiOperation(value = "按id修改数据")
        //@ApiImplicitParams()
        public ResultDTO updateById( @RequestBody Appointment appointment)throws Exception{
            try {
                appointmentService.update(appointment);
            } catch (Exception e) {
                return ResultUtil.Error("500",e.getMessage());
            }
            return ResultUtil.Success(appointmentService.get(appointment.getAppointmentId()));

        }

        @GetMapping("/deleteById/{id}")
        @ApiOperation("按id删除数据")
        @ApiImplicitParams({
                @ApiImplicitParam(paramType = "path", name = "id", dataType = "string", required = true, value = "实体类id"),

        })
        public ResultDTO deleteById(@RequestParam(required = true) @PathVariable("id") String id)throws Exception{
            Appointment oldAppointment = null;
            try {
                oldAppointment = appointmentService.get(id);
                appointmentService.deleteById(id);
            } catch (Exception e) {
                return ResultUtil.Error("500",e.getMessage());
            }
            return ResultUtil.Success(oldAppointment);
        }

        @PostMapping("/getAppointmentPage")
        @ApiOperation("按条件查询，分页")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "pageNum", dataType = "Integer", defaultValue = "1", required = false, value = "页码"),
                @ApiImplicitParam(name = "pageSize", dataType = "Integer", defaultValue = "10", required = false, value = "每页容量")
        })
        public ResultDTO selectEntityPage(@RequestBody AppointmentRequestDTO appointmentRequestDTO)throws Exception{

            PageList<AppointmentRespondDTO> PageList = null;
            try {
                Appointment appointment = new Appointment();
                System.out.println(appointmentRequestDTO.TranToAppointment(appointment));
                Appointment tranToAppointment = appointmentRequestDTO.TranToAppointment(appointment);
                PageList<Appointment> pageData = appointmentService.findPageData(tranToAppointment,
                                                                                        appointmentRequestDTO.getPageNum(),
                                                                                        appointmentRequestDTO.getPageSize(),
                                                                                "creat_time DESC");
                ArrayList<AppointmentRespondDTO> data = new ArrayList<>();
                for (Appointment item : pageData.getData()) {
                    Vaccine vaccine = vaccineService.get(item.getVaccineId());
                    data.add(new AppointmentRespondDTO(item,vaccine.getVaccineName(),vaccine.getVaccineId()));
                }
                PageList = new PageList<AppointmentRespondDTO>(data,pageData.getPageNum(),pageData.getPageSize(),pageData.getTotalItems());
            } catch (Exception e) {
                return ResultUtil.Error("500",e.getMessage());
            }
            return ResultUtil.Success(PageList);

        }

        @PostMapping("/getAppointment")
        @ApiOperation("按条件查询，不分页")
        //@ApiImplicitParams()
        public ResultDTO selectEntityPage( @RequestBody Appointment appointment)throws Exception{
            List<Appointment> appointmentList = null;
            try {
                appointmentList = appointmentService.findByParams(appointment);
            } catch (Exception e) {
                return ResultUtil.Error("500",e.getMessage());
            }
            return ResultUtil.Success(appointmentList);
        }


}
